package com.zr.daoimpl;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.zr.dao.Functiondao;
import com.zr.model.Function;
import com.zr.model.Role;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;




@Repository("functionDao")
public class FunctiondaoimplSCM extends BaseDaOImpl implements Functiondao{

	/**
	 * 获取功能对象
	 *
	 **/
	@Override
	public JSONArray getFunctionByPidFids(int pid, String fid) {
		
		JSONArray j=new JSONArray();
		String hql = " from Function f where f.pid=:pid and fid in ("+fid+")";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setInteger("pid", pid);	
		List<Function>  obj = query.list();	
		Iterator<Function> it = obj.iterator();
		while(it.hasNext()) {
			JSONObject js=new JSONObject();
			Function f=it.next();
			js.put("id",f.getFid());
			js.put("text", 	f.getFname());
			js.put("state", f.getFstate());
			JSONObject atter =new JSONObject();
			atter.put("furl",f.getFurl());
			js.put("attributes", atter);
			j.add(js);					  
		}		
		return j;
	}

	/**
	 * 
	 * 获取子功能，根据递归
	 * 
	 */	
	@Override
	public JSONArray getfunctions(int pid, String fids) {
		JSONArray j=this.getFunctionByPidFids(pid, fids);
		for(int i=0;i<j.size();i++){
			String state=j.getJSONObject(i).getString("state");
		if("open".equals(state)){
			continue;
		}else{
			int cu=j.getJSONObject(i).getInt("id");
			JSONArray children = this.getfunctions(cu,fids);
			j.getJSONObject(i).put("children", children);						
		}			
		}
		return j;
	}

	
	/**
	 * 根据uid获取role对象的fids
	 * 
	 * */
	@Override
	public Role getfidsByUid(int rid) {		
		Role r=new Role();
	    Role t = (Role) this.getCurrentSession().get(Role.class, Integer.valueOf(rid));
		return  t;
	}

}
